package org.jeecg.modules.platformMasterEndPoint.controller;


import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.modules.platformMasterEndPoint.entity.JxCouponDo;
import org.jeecg.modules.platformMasterEndPoint.mapper.JxCouponMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@Api(tags = "营销功能")
@RestController
@RequestMapping("/jx/jxMarketing")
@Slf4j
public class JxMarketingController {

    @Autowired
    private JxCouponMapper jxCouponMapper;

    @PostMapping("/createOrUpdateCoupon")
    public Result<?> createOrUpdateCoupon(@RequestBody()JSONObject requestBody) {

        String couponId = requestBody.getString("couponId");
        if (couponId == null || couponId.isEmpty()) {
            // 当请求参数中不包含 couponId时，表示创建新优惠券
            JxCouponDo newCoupon = buildCouponInfo(requestBody);
            int count = jxCouponMapper.insert(newCoupon);
            if (count == 1) {
                log.info("添加新优惠券成功，优惠券id: {}" , newCoupon.getId());
                JSONObject resultData = new JSONObject();
                resultData.put("couponId", newCoupon.getId());
                return Result.ok(resultData);
            } else {
                log.error("添加失败");
                return Result.error("添加失败");
            }
        } else {
            // 当请求参数中包含 couponId时，表示更新已有优惠券信息
            JxCouponDo updatedCoupon = buildCouponInfo(requestBody);
            updatedCoupon.setId(couponId);

            int count = jxCouponMapper.updateById(updatedCoupon);
            if (count == 1) {
                log.info("优惠券更新成功，优惠券id: {}" , couponId);
                return Result.ok("优惠券更新成功");
            } else {
                log.error("优惠券更新失败");
                return Result.error("优惠券更新成功失败");
            }
        }
    }

    private JxCouponDo buildCouponInfo(JSONObject requestBody) {
        JxCouponDo jxCouponDo = new JxCouponDo();
        jxCouponDo.setCouponName(requestBody.getString("couponName"));
        jxCouponDo.setCouponValue(requestBody.getInteger("couponValue"));
        jxCouponDo.setAmountPerUser(requestBody.getShortValue("amountPerUser"));
        jxCouponDo.setExpiredAt(requestBody.getDate("expiredAt"));
        jxCouponDo.setSiteIds("*");
        jxCouponDo.setStoreIds("*");
        jxCouponDo.setCouponFee(requestBody.getJSONArray("couponFee").toJSONString());
        jxCouponDo.setCreateTime(new Date());

        return jxCouponDo;
    }


    @PostMapping("/createOrUpdateCouponStyle")
    public Result<?> createOrUpdateCouponStyle(@RequestBody()JSONObject requestBody) {

        return null;
    }

    @PostMapping("/deleteCouponStyleById")
    public Result<?> deleteCouponStyleById(@RequestParam("couponId") String couponId) {

        return null;
    }

}
